#include "flapp_system.h"
#include "system_task.h"
#include "at32f421.h" 

////////////////////////////////////////////////////////////////////////////////////////////////////
//how to use
// 1-4 add to platform
// 1. add 'System_Tick_Counter++;' to system timer handel
// 2. add 'Sys_Task_CheckValid();' at the program beginng after system init, but not nesscessly.(check _SYS_TASK_NEED_CHECKVAILD_)
// 3. add 'Sys_Task_Timer_Scan();' to main loop
// 4. add 'Sys_Task_Process();' to main loop

// after step 4, user can only run step 5 and 6
// 5. add element to SYS_TASK_NUM_ENUM
// 6. add and init element in Sys_Task array


//use func. of Sys_Task_CheckValid() or not
//0: not use, 1: use
#define _SYS_TASK_NEED_CHECKVAILD_ 0

//must add to system timer handle
volatile u32 System_Tick_Counter = 0; 
static u32 System_Tick_Counter_Mark = 0;
static u16 Sys_Task_Event = 0;

#include "system_task_user.c"
 
//func had better use at the begin of the system, but not nesscessly
//func for check the function point and time count in the task 
#if (_SYS_TASK_NEED_CHECKVAILD_)
void Sys_Task_CheckValid(void)
{
  u8 i = 0;
  for(i=0; i<SYS_TASK_NUM_ENUM_END; i++)
  {
    if(Sys_Task[i].Func == NULL)
    {
      printf("\r\n-----Error System halt, task %d func is null-----", i);
      printf("\r\n-----Error pls check SYS_TASK_NUM_ENUM & Sys_Task[SYS_TASK_NUM_ENUM_END]-----");
      while(1);
    }

    if(Sys_Task[i].Sys_Task_Time_Count == 0)
    {
        printf("\r\n++++++++Warning System halt, task%d Sys_Task_Time_Count is '0'++++++++", i);
    }
  }

  printf("\r\n Sys_Task_CheckValid OK");
}
#else
void Sys_Task_CheckValid(void)
{}
#endif


//timer handle
//calculate the time of system and task , and set the flag of task that time up
void Sys_Task_Timer_Scan(void)
{
	u32 Temp_Time_Count = 0;
	u8 i = 0;

	//calculate how many time one time in system main loop 
	if(System_Tick_Counter != System_Tick_Counter_Mark)
	{
		if(System_Tick_Counter >= System_Tick_Counter_Mark)
		{
			Temp_Time_Count = (u32)(System_Tick_Counter - System_Tick_Counter_Mark);
		}
		else
		{
			Temp_Time_Count =	(u32)(0xFFFFFFFF - System_Tick_Counter_Mark + System_Tick_Counter);
		}

		//which task time's up?
		for(i=0; i<SYS_TASK_NUM_ENUM_END; i++)
		{
			Sys_Task[i].Sys_Task_Time_Counter += Temp_Time_Count;

			if(Sys_Task[i].Sys_Task_Time_Counter >= Sys_Task[i].Sys_Task_Time_Count)
			{
					Sys_Task[i].Sys_Task_Time_Counter = 0;

					//set task flag
					SETBIT_VAL(Sys_Task_Event, i);
			}
		}

		System_Tick_Counter_Mark = System_Tick_Counter;
	}
}

//this function should be in the main loop
//task time's up, it should run task function
void Sys_Task_Process(void)
{
	u8 i;
	if(Sys_Task_Event)
	{
		for(i=0; i<SYS_TASK_NUM_ENUM_END; i++)
		{
			if(GETBIT_VAL(Sys_Task_Event, i))
			{
				Sys_Task[i].Func();
				CLRBIT_VAL(Sys_Task_Event, i);
			}
		}
	}
}


//////////////////////////////////////////////////////////////////////////////////////////////////////

